/*
 * @Author: 
 * @Date: 2022-02-16 09:36:15
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-16 11:38:28
 * @Description: 请填写简介
 */
import React, { createContext, useContext, forwardRef } from 'react'
import { Button } from 'antd'

const themes = {
  dark: {
    foreground: '#222',
    background: '#fff'
  },
  light: {
    foreground: '#eee',
    background: '#000'
  }
}

const ThemeContext = createContext({
  theme: themes.dark,
  toggleTheme: () => {}
})

const FancyButton = forwardRef((props, ref) => {
  return (
    <Button ref={ref} className="ml10" {...props}>{props.children}</Button>
  )
})

class ThemeButton extends React.Component {
  // static contextType = ThemeContext
  // componentDidMount() {
  //   console.log(this.context, '1')
  // }
  render() {
    let props = this.props
    // let theme = this.context
    return (
      <ThemeContext.Consumer>
        {
          value => {
            {/* return <Button {...props} style={{ background: value.background, color: value.foreground }} /> */}
            return <Button
                      {...props}
                      className="ml10"
                      style={{ background: value.theme.background, color: value.theme.foreground }}
                      onClick={value.toggleTheme}
                    />
          }
        }
      </ThemeContext.Consumer>
      // <Button {...props} style={{ background: theme.background, color: theme.foreground }}></Button>
    )
  }
}
// ThemeButton.contextType = ThemeContext

function Toolbar(props) {
  const theme = useContext(ThemeContext)
  // console.log(theme, 't')
  return (
    <ThemeButton>
    {/* <ThemeButton onClick={props.changeTheme}> */}
      Change Theme
    </ThemeButton>
  )
}

export default class UpdateTheme extends React.Component {
  refDom = React.createRef()
  constructor(props) {
    super(props)
    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }))
    }
    this.state = {
      theme: themes.light,
      toggleTheme: this.toggleTheme
    }
    this.handleFancy = () => {
      console.log(this.refDom)
    }
  }
  render () {
    return (
      <>
        <ThemeContext.Provider value={this.state}>
          <Toolbar />
          {/* <Toolbar changeTheme={this.toggleTheme}></Toolbar> */}
        </ThemeContext.Provider>
        <FancyButton ref={this.refDom} onClick={this.handleFancy}>click me</FancyButton>
      </>
    )
  }
}